package com.gxc.core.validate.code;

import com.gxc.core.content.SessionContent;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author GongXincheng
 * @since 2019-10-16 16:13
 */
@RestController
public class SmsCodeController {

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @GetMapping("/code/sms")
    public String getSmsCode(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {

        String mobile = ServletRequestUtils.getRequiredStringParameter(request, "mobile");
        String code = RandomStringUtils.randomNumeric(6);
        System.out.println(String.format("手机号：%s, 手机验证码：%s", mobile, code));

        Map<String,Object> map = new HashMap<>(2);
        map.put(mobile, code);
        sessionStrategy.setAttribute(new ServletWebRequest(request), SessionContent.SMS_CODE_SESSION_KEY, map);

        return "success";
    }

}
